<?php

namespace App\Console\Commands;

use App\Models\Agent;
use App\Models\Base;
use App\Models\OldSystem\Aftersale;
use App\Models\OldSystem\Order;
use App\Models\OldSystem\User;
use App\Models\OldSystem\UserCopartner;
use App\Models\OldSystem\UserWithdrawal;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Hash;

class MigrateOldSystemAgentBasicData extends Command
{
    /**
     * 原有系统对应现有系统的 代理商等级关系 map
     * @var array
     */
    const AGENT_LEVEL_MAP = [
        'one' => Agent::LEVEL_STRONGMAN,
        'two' => Agent::LEVEL_ELITE,
        'three' => Agent::LEVEL_GROUP_OWNER,
    ];

    /**
     * 原有系统对应现有系统的 代理商状态 map
     */
    const AGENT_STATUS_MAP = [
        1 => Agent::STATUS_NORMAL,
        0 => Agent::STATUS_DISABLE,
    ];

    /**
     * 命令名称及签名
     *
     * @var string
     */
    protected $signature = 'migrate:agent_basic';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '迁移老系统的代理商数据';

    /**
     * 代理商总数
     * @var int
     */
    protected $agentCount = 0;

    public function handle()
    {
        /**
         * 整体迁移脚本分三部分,按照顺序执行
         * 一. 代理基本信息 (当前)
         * 二. 代理个人业绩 (优化为 可以分多个进程执行) MigrateOldSystemAgentPerformance
         * 三. 团队业绩 (优化为 可以分多个进程执行) MigrateOldSystemAgentTeamPerformance
         */
        try {
            // 简单的启动自检
            if (Agent::query()->first()) {
                throw new \RuntimeException('该脚本只处理代理商初始化迁移,没有做重复执行的兼容');
            }

            \DB::beginTransaction();

            $this->agentCount = User::query()->count();
            $bar = $this->output->createProgressBar($this->agentCount);
            $bar->start();
            User::query()
                ->with([
                    'partner' => function (HasOne $hasOne) {
                        $hasOne->whereIn('copartner_level', ['G', 'A']); // 只同步 GA 合伙人
                    }])
                ->chunk(4000, function (Collection $users) use ($bar) {
                    $agentInsert = [];
                    $users->each(function (User $user) use ($bar, &$agentInsert) {
                        // 先同步 sdj_user 表
                        $userTemp = [
                            'id' => $user['user_id'],
                            'name' => $user['name'],
                            'phone' => $user['username'],
                            'password' => 'password', // Hash make 也挺耗时的, 也脱离出来, 这里字段不能为空, 随意填一个
                            'level' => self::AGENT_LEVEL_MAP[$user['level']],
                            'wechat_number' => $user['wechat'],
                            'balance' => (int) $user['balance'] * Base::CURRENCY_UNIT_CONVERSION, // 现有系统金额单位为分
                            'unextractable_balance' => (int) ($user['overdraft'] * Base::CURRENCY_UNIT_CONVERSION), // 现有系统金额单位为分
                            'direct_inviter' => $user['inviter_direct'],
                            'indirect_inviter' => $user['inviter_indirect'],
                            'affiliated_partner' => $user['user_id_copartner'],
                            'invitation_code' => $user['user_sn'],
                            'login_frequency' => $user['login_count'],
                            'status' => self::AGENT_STATUS_MAP[$user['status']] ?? Agent::STATUS_NORMAL,
                            'created_at' => $user['add_time'] === 0 ? null : Carbon::createFromTimestamp($user['add_time']),
                            'updated_at' => $user['update_time'] === 0 ? null : Carbon::createFromTimestamp($user['update_time']),
                        ];

                        if (!empty($user->partner)) {
                            $agent = Agent::query()->create($userTemp);
                            $agent->partnerIdentity()->create([
                                'id' => $user->partner['user_copartner_id'],
                                'level' => UserCopartner::LEVEL_MAP_CONTROL[$user->partner['copartner_level']],
                                'created_at' => $user->partner['add_time'] === 0 ? null : Carbon::createFromTimestamp($user->partner['add_time']),
                                'updated_at' => $user->partner['update_time'] === 0 ? null : Carbon::createFromTimestamp($user->partner['update_time']),
                                'deleted_at' => $user->partner['status'] === 2 ? Carbon::createFromTimestamp($user->partner['update_time']) : null // 状态是无效的话 在新系统就当做删除
                            ]);
                        } else {
                            $agentInsert[] = $userTemp;
                        }

                        $bar->advance(1);
                    });

                    Agent::query()->insert($agentInsert);
                });
            $bar->finish();

            \DB::commit();
            $this->output->success('迁移代理基本数据完成!');
        } catch (\Exception $e) {
            \DB::rollBack();
            $this->output->error($e->getMessage());
        }
    }
}
